package com.yohann.algorithm;

/**
 * <p>
 * 双向链表（约瑟夫问题）
 * </p>
 *
 * @author Yohann
 * @since 2020/9/22
 */
public class JosepfuTest {
    public static void main(String[] args) {
        CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
        System.out.println("**************");
        circleSingleLinkedList.countBoy(1,2,5);
        circleSingleLinkedList.display();
    }
}

class CircleSingleLinkedList{
    private Boy first;

    public void addBoy(int nums){
        if(nums < 1){
            System.out.println("个数有误");
            return;
        }

        Boy current = null;
        for (int i = 1; i < nums+1; i++) {
            //根据编号创建小孩节点
            Boy boy = new Boy(i);

            if (i == 1){
                first = boy;
                first.setNext(first);
                current = first;
            }else {
                //当前的节点指向新节点
                current.setNext(boy);
                //新节点最后指向第一个节点
                boy.setNext(first);
                //更新当前尾部指向
                current = boy;
            }
        }
    }

    public void display(){
        if (first == null){
            System.out.println("链表为空！");
            return;
        }

        Boy current = first;
        while (true){
            System.out.println(current);
            if (current.getNext() == first){
                break;
            }
            current = current.getNext();
        }
    }

    public void countBoy(int startNo, int countNum, int nums){
        addBoy(nums);

        if (first == null || startNo < 1 || startNo > nums){
            System.out.println("出错！");
            return;
        }

        //创建一个辅助指针,下一个指向first
        Boy helper = first;
        while (true){
            if (helper.getNext() == first){
                break;
            }
            helper = helper.getNext();
        }

        //移动到起点位置
        for (int i = 0; i < startNo-1; i++) {
            first = first.getNext();
            helper = helper.getNext();
        }

        //开始出圈
        while (true){
            if (helper == first) {
                break;
            }

            for (int i = 0; i < countNum-1; i++) {
                first = first.getNext();
                helper = helper.getNext();
            }

            System.out.println(first+"移除");

            first = first.getNext();
            helper.setNext(first);
        }
    }
}

class Boy{
    private int no;
    private Boy next;

    public Boy(int no) {
        this.no = no;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public Boy getNext() {
        return next;
    }

    public void setNext(Boy next) {
        this.next = next;
    }

    @Override
    public String toString() {
        return "Boy{" +
                "no=" + no +
                '}';
    }
}